from sqlalchemy.orm import Session
from schema import Farm_schema
from model import Farm_model



def get_Farm(db: Session, ID: int):
    return db.query(Farm_model.Farm).filter(Farm_model.Farm.ID == ID).first()


def get_all_Farm(db: Session):
    return db.query(Farm_model.Farm).all()


def delete_Farm(db: Session, ID):
    to_delete = db.query(Farm_model.Farm).filter(Farm_model.Farm.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Farm(db: Session, Farm: Farm_schema.Farm):
    db_Farm = Farm_model.Farm(
        Name=Farm.Name,
        Address=Farm.Address,
        TotalArea=Farm.TotalArea,
        GeoRange=Farm.GeoRange,
    )
    db.add(db_Farm)
    db.commit()
    db.refresh(db_Farm)
    return db_Farm


def update_Farm(db: Session, ID, field_name, new_value):
    db_Farm = db.query(Farm_model.Farm).filter(Farm_model.Farm.ID == ID).first()
    setattr(db_Farm, field_name, new_value)
    db.commit()
    db.refresh(db_Farm)
    return db_Farm
